package lion.framework.core.web.path;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lion.dev.lang.MapJ;
import lion.framework.core.conf.Config;
import lion.framework.core.conf.ConfigManager;

/**
 * 路径变量处理类，在路径中，以#{var}这样的路径，在framework.xml中可以这样配置
 *
 * <pre>
 * <framework>
 * 		<web>
 * 			<pathvar name="varname" value="varvalue" />
 * 		</web>
 * </framework>
 * </pre>
 *
 * 如果路径中有变量，而变量没有在framework.xml中进行配置，那么路径将会使用#{var}中的var作为当前路径变量的值。
 *
 * <pre>
 * time   2013 2013年12月6日 上午11:23:46
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
public class PathVar {

	private static final Pattern pathVarPattern = Pattern.compile("#\\{(\\w+)\\}");
	private static Map<String, String> pathvars;

	/**
	 * 替换路径中的变量,如果没有找到配置的变量值，则使用路径#{var}中的var作为路径
	 */
	public static String replacePathVars(String pathm) {

		Map<String, String> pathvars = getPathVars();
		if (pathvars == null) { return pathm; }

		Matcher m = pathVarPattern.matcher(pathm);
		StringBuffer sbu = new StringBuffer();
		String key;
		String value;
		while (m.find()) {
			key = m.group(1);
			value = pathvars.get(key);
			if (value == null) {
				value = key;
			}
			m.appendReplacement(sbu, value);
		}
		m.appendTail(sbu);

		return sbu.toString();
	}

	public static Map<String, String> getPathVars() {

		if (pathvars == null) {
			synchronized (pathVarPattern) {
				if (pathvars == null) {
					pathvars = new HashMap<>();
					Config config = ConfigManager.getConfig("framework");
					List<MapJ> vars = config.getList("framework.web.pathvar");
					for (MapJ pathvar : vars) {
						String val = pathvar.getString("value");
						if (val == null) {
							val = pathvar.getString("name");
						}
						pathvars.put(pathvar.getString("name").toLowerCase(), val.toLowerCase());
					}
				}
			}
		}
		return pathvars;
	}

	public static String getVar(String name) {

		String result = pathvars.get(name);
		if (result == null) {
			result = name;
		}
		return result;
	}

	public static void setVar(String name, String value) {

		Map<String, String> pathvars = getPathVars();
		pathvars.put(name, value);
	}

	public static void setVars(Map<String, String> params) {

		Map<String, String> pathvars = getPathVars();

		pathvars.putAll(params);
	}
}
